//
//  ViewController.swift
//  1.17.Displaying Long Lines of Text with UITextView
//
//  Created by joker on 15/7/22.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var textView: UITextView?
    let defaultContentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
/* #1 */
        //        textView = UITextView(frame: view.frame)
//        if let theTextView = textView {
//            theTextView.text = "Some text goes here ..."
//            theTextView.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
//            theTextView.font = UIFont.systemFontOfSize(16)
//        view.addSubview(theTextView)
//        }
        
        /* #2 */
        textView = UITextView(frame: view.bounds)
        if let theTextView = textView {
            theTextView.text = "Some text goes here ..."
            theTextView.font = UIFont.systemFontOfSize(16)
            theTextView.contentInset = defaultContentInset
            
            view.addSubview(theTextView)
            
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleKeyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleKeyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
        }
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func handleKeyboardDidShow(notificaton: NSNotification) {
        let keyboardRectAsObject = notificaton.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        
        var keyboardRect = CGRectZero
        
        keyboardRectAsObject.getValue(&keyboardRect)
        
        textView!.contentInset = UIEdgeInsets(top: defaultContentInset.top, left: 0, bottom: keyboardRect.height, right: 0)
    }
    func handleKeyboardWillHide(notificaton: NSNotification ){
        textView!.contentInset = defaultContentInset
    }


}

